package cool.taomu.toolkit.velocity

import java.io.File
import java.io.StringWriter
import java.util.Map
import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.VelocityEngine
import org.slf4j.LoggerFactory
import cool.taomu.toolkit.template.ITemplate

class VelocityUtils implements ITemplate{
	val static LOG = LoggerFactory.getLogger(VelocityUtils);

	override execute(String path, Map<String, Object> dataModel) {
		var subPath = path.substring(0, path.lastIndexOf(File.separator) + 1);
		var template = path.substring(path.lastIndexOf(File.separator) + 1);
		return velocity(subPath, template, dataModel);
	}

	def velocity(String basePath, String template, Map<String, Object> dataModel) {
		var StringWriter writer = new StringWriter();
		try {
			var ve = new VelocityEngine();
			ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, basePath);
			ve.init();
			val VelocityContext context = new VelocityContext();
			dataModel.forEach [ k, v |
				context.put(k, v);
			]
			ve.getTemplate(template, "UTF-8").merge(context, writer);
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		}
		return writer;
	}

}
